package cn.ulyer.common.transcode.secret;


import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;

import java.nio.charset.StandardCharsets;

/**
 * RSA处理
 */
public class RSAHandler implements TranscodeHandler{


    @Override
    public String encryptHex(Object key, String sourceText) {
        RSA rsa = new RSA((String) key,null);
        byte[] encrypt = rsa.encrypt(sourceText, KeyType.PublicKey);
        return HexUtil.encodeHexStr(encrypt);
    }

    @Override
    public String decrypt(Object key, String cipherText) {
        String privateKey = (String) key;
        RSA rsa = new RSA(privateKey,null);
        byte[] source = rsa.decrypt(SecureUtil.decode(cipherText), KeyType.PrivateKey);
        return new String(source, StandardCharsets.UTF_8);
    }

    @Override
    public String algorithm() {
        return "RSA";
    }

    @Override
    public byte[] signature(Object key, String source) {
        Sign sign = new Sign(SignAlgorithm.SHA256withRSA, (String) key, null);
        return sign.sign(source);
    }

    @Override
    public boolean verifySign(Object key, String source, String signData) {
        Sign sign = new Sign(SignAlgorithm.SHA256withRSA, (String) key, null);
        return sign.verify(source.getBytes(StandardCharsets.UTF_8), SecureUtil.decode(signData));
    }
}
